package com.vodlee.flowlayoutlib;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class FlowLayout extends ViewGroup {
    private static final String TAG = "FlowLayout";

    // TODO: 2020/7/22 init manager by builder
    private FlowLayoutManager manager = FlowLayoutManager.getDefaultManager();

    private List<SingleLineViews> viewLines;

    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public FlowLayout setLayoutManager(FlowLayoutManager manager) {
        if (manager == null) {
            return this;
        }
        this.manager = manager;
        return this;
    }

    private void initMeasure() {
        if (viewLines == null) {
            viewLines = new ArrayList<>();
        } else {
            viewLines.clear();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        initMeasure();

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int minWidth = 0;
        int minHeight = 0;

        SingleLineViews line = new SingleLineViews();

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            // measure child
            measureChild(widthMeasureSpec, heightMeasureSpec, line, child);
            if (child.getVisibility() == View.GONE) {
                continue;
            }
            // get measure size with margin
            int childWidthWithMargin = getChildMeasureWidth(child);
            int childHeightWithMargin = getChildMeasureHeight(child);
            if (line.width + manager.getHorizentalDivider() + childWidthWithMargin > widthSize - getPaddingLeft() - getPaddingRight()) {
                // add line
                minHeight += line.height + manager.getVerticalDivider() - manager.getHorizentalDivider();
                minWidth = Math.max(minWidth, line.width);
                viewLines.add(line);

                line = new SingleLineViews();
                // measure child twice, because the widthUsed and heightUsed is changed
                measureChild(widthMeasureSpec, heightMeasureSpec, line, child);
                childWidthWithMargin = getChildMeasureWidth(child);
                childHeightWithMargin = getChildMeasureHeight(child);
            }
            line.views.add(child);
            line.height = Math.max(childHeightWithMargin, line.height);
            line.width += childWidthWithMargin + manager.getHorizentalDivider();

            if (i == getChildCount() - 1) {
                minHeight += line.height;
                minWidth = Math.max(minWidth, line.width);
                viewLines.add(line);
            }
        }

        int realWidth = (widthMode == MeasureSpec.EXACTLY) ? widthSize : minWidth;
        int realHeight = (heightMode == MeasureSpec.EXACTLY) ? heightSize : minHeight;

        setMeasuredDimension(realWidth, realHeight);
    }

    private int getChildMeasureWidth(View child) {
        int childWidthWithMargin = child.getMeasuredWidth();
        if (child.getLayoutParams() instanceof MarginLayoutParams) {
            MarginLayoutParams params = (MarginLayoutParams) child.getLayoutParams();
            childWidthWithMargin += params.leftMargin + params.rightMargin;
        }
        return childWidthWithMargin;
    }

    private int getChildMeasureHeight(View child) {
        int childHeightWithMargin = child.getMeasuredHeight();
        if (child.getLayoutParams() instanceof MarginLayoutParams) {
            MarginLayoutParams params = (MarginLayoutParams) child.getLayoutParams();
            childHeightWithMargin += params.topMargin + params.bottomMargin;
        }
        return childHeightWithMargin;
    }

    private void measureChild(int widthMeasureSpec, int heightMeasureSpec, SingleLineViews line, View child) {
        if (child.getLayoutParams() instanceof MarginLayoutParams) {
            measureChildWithMargins(child, widthMeasureSpec, line.width, heightMeasureSpec, 0);
        } else {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int lineCount = viewLines.size();
        int curL = getPaddingLeft();
        Log.d(TAG, "onLayout: getLeft(): " + getLeft());
        int curT = getPaddingTop();
        Log.d(TAG, "onLayout: getTop(): " + getTop());
        for (int i = 0; i < lineCount; i++) {
            SingleLineViews line = viewLines.get(i);
            int lineHeight = line.height;
            for (int j = 0; j < line.views.size(); j++) {
                View view = line.views.get(j);
                int left = curL;
                int top = curT;
                if (view.getLayoutParams() instanceof MarginLayoutParams) {
                    MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
                    left += params.leftMargin;
                    top += params.topMargin;
                }

                int bottom = top + view.getMeasuredHeight();
                int right = left + view.getMeasuredWidth();
                if (view.getVisibility() == VISIBLE) {
                    view.layout(left, top, right, bottom);
                }
                curL = right + manager.getHorizentalDivider();
                if (view.getLayoutParams() instanceof MarginLayoutParams) {
                    MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
                    curL += params.rightMargin;
                }
            }
            curL = getPaddingLeft();
            curT = curT + lineHeight + manager.getVerticalDivider();
        }
    }

    @Override
    protected FlowLayoutParams generateDefaultLayoutParams() {
        return new FlowLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    private class SingleLineViews {
        private List<View> views;
        public int height;
        public int width;

        public SingleLineViews() {
            views = new ArrayList<>();
            height = 0;
            width = 0;
        }
    }

    public static class FlowLayoutParams extends MarginLayoutParams {

        public FlowLayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public FlowLayoutParams(int width, int height) {
            super(width, height);
        }
    }
}
